import React, { useState, useCallback } from 'react';
import { Button, message } from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import MDEditor from '@uiw/react-md-editor';
import '@uiw/react-md-editor/markdown-editor.css';
import '@uiw/react-markdown-preview/markdown.css';
import rehypeSanitize from 'rehype-sanitize';

const MarkdownEditor = ({ initialContent = '', onSave }) => {
  const [content, setContent] = useState(initialContent);
  const [saving, setSaving] = useState(false);

  const handleSave = useCallback(async () => {
    if (!content.trim()) {
      message.warning('文档内容不能为空');
      return;
    }
    
    try {
      setSaving(true);
      const success = onSave ? await onSave(content) : false;
      if (success) {
        message.success('文档保存成功');
      }
      return success;
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败，请稍后重试');
      return false;
    } finally {
      setSaving(false);
    }
  }, [content, onSave]);

  const handleChange = useCallback((value) => {
    setContent(value || '');
  }, []);

  return (
    <div className="markdown-editor-container">
      <div className="editor-toolbar">
        <div className="editor-actions">
          <Button 
            type="primary" 
            icon={<SaveOutlined />} 
            onClick={handleSave}
            size="small"
            loading={saving}
            disabled={saving}
          >
            {saving ? '保存中...' : '保存'}
          </Button>
        </div>
      </div>
      <div className="markdown-editor">
        <MDEditor
          value={content}
          onChange={handleChange}
          previewOptions={{
            rehypePlugins: [[rehypeSanitize]],
          }}
          height={400}
          visibleDragbar={false}
        />
      </div>
      <div className="markdown-preview">
        {/* <div className="preview-title">预览</div>
        <div className="preview-content">
          <MDEditor.Markdown source={content} style={{ whiteSpace: 'pre-wrap' }} />
        </div> */}
      </div>
    </div>
  );
};

export default MarkdownEditor;
